package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"
	"xialou_platform/services/agent/rpc/agent"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentUserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentUserListLogic {
	return AgentUserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentUserListLogic) AgentUserList(req *types.AgentUserListReq) (resp *respx.PageResp, err error) {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}

	listResp, err := l.svcCtx.AgentRpc.AgentUserList(l.ctx, &agent.AgentUserListReq{
		Page:       req.Page,
		PageSize:   req.PageSize,
		Status:     1,
		AgentId:    uid,
		SourceType: req.SourceType,
	})
	if err != nil {
		return nil, err
	}

	res := make([]*types.AgentUserListResp, 0)
	var ids []int64
	for _, agentUser := range listResp.Data.List {
		idStr := respx.IDFrom(agentUser.UserId).ToString()
		temp := &types.AgentUserListResp{
			Id:         idStr,
			Nickname:   fmt.Sprintf("%s%s", "Gfner", idStr[len(idStr)-6:]),
			Avatar:     "https://imgs.ynz666.com/xiuxian/avatar.png",
			SourceType: agentUser.SourceType,
			CreateTime: tools.TimeUnixShowLayoutString(agentUser.CreateTime),
		}
		ids = append(ids, agentUser.UserId)
		res = append(res, temp)
	}

	bs, err := json.Marshal(map[string]interface{}{
		"ids": ids,
	})
	if err != nil {
		l.Error(err.Error())
		return nil, err
	}
	apiResp, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.UserInfo,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(bs),
		l.svcCtx.Config.Auth.AccessExpire,
		10000)
	if err != nil {
		l.Error(err.Error())
		return nil, err
	}
	//r, err := tools.Post(l.svcCtx.Config.XiuXianApi.UserInfo, map[string]interface{}{
	//	"ids": ids,
	//})
	//if err != nil {
	//	l.Error(err.Error())
	//	return nil, err
	//}
	//apiResp, err := io.ReadAll(r.Body)
	//if err != nil {
	//	l.Error(err.Error())
	//	return nil, err
	//}
	l.Info("xiuxianbaapi response: ", string(apiResp))
	var apiRespModel userApiResp
	if err = json.Unmarshal(apiResp, &apiRespModel); err != nil {
		l.Error(err.Error())
		return nil, err
	}
	if apiRespModel.Data.Code != 0 || apiRespModel.Code != 200 {
		l.Error(apiRespModel.Message)
		return nil, fmt.Errorf(apiRespModel.Message)
	}
	for i, user := range res {
		for _, apiUser := range apiRespModel.Data.List {
			if user.Id == fmt.Sprintf("%d", apiUser.ID) {
				res[i].Nickname = apiUser.NickName
			}
		}
	}

	return respx.NewPageResp(req.Page, req.PageSize, listResp.Data.Total, res), nil
}

type userApiResp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		Code    int    `json:"code"`
		Message string `json:"message"`
		Total   int    `json:"total"`
		List    []struct {
			ID       int64  `json:"id"`
			NickName string `json:"nickName"`
			Avatar   string `json:"avatar"`
		} `json:"list"`
	} `json:"data"`
}
